const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const OpenAI = require('openai');
const rateLimit = require('express-rate-limit');
// require('dotenv').config();

const app = express();
const port = 3000;

// 配置速率限制 (QPS=2)
const limiter = rateLimit({
  windowMs: 1000, // 1秒窗口
  max: 2, // 每个窗口最多2个请求
  message: {
    error: '请求过于频繁，请每秒不超过2次请求',
    status: 429
  },
  standardHeaders: true,
  legacyHeaders: false,
});

// 中间件

app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json());
app.use(cors());

// 初始化 OpenAI 客户端
const openai = new OpenAI({
  baseURL: 'https://api.deepseek.com',
  apiKey: 'sk-85708eb7d0b14ccb83d6d6ca3320a62d'
});

// 健康检查端点
app.get('/', (req, res) => {
  res.json({ status: 'API is running with SSE support' });
});

// SSE 聊天接口
app.post('/api/chat-sse', limiter, async (req, res) => {
  try {
    const { messages, model = 'deepseek-chat' } = req.body;
    console.log(messages);
    
    if (!messages || !Array.isArray(messages)) {
      return res.status(400).json({ error: 'Messages array is required' });
    }

    // // 设置 SSE 响应头
    res.setHeader('Content-Type', 'text/event-stream');
    res.setHeader('Cache-Control', 'no-cache');
    res.setHeader('Connection', 'keep-alive');
    res.flushHeaders();

    // // 发送初始事件
    res.write(`event: status\ndata: ${JSON.stringify({ status: 'connecting' })}\n\n`);

    // 调用 DeepSeek API 并转发流式响应
    const stream = await openai.chat.completions.create({
      messages,
      model,
      stream: true // 启用流式响应
    });

    // 转发流数据
    for await (const chunk of stream) {
      const content = chunk.choices[0]?.delta?.content || '';
      if (content) {
        res.write(`data: ${JSON.stringify({ content })}\n\n`);
      }
    }

    // 发送结束事件
    res.write(`event: end\ndata: ${JSON.stringify({ status: 'completed' })}\n\n`);
    res.end();
  } catch (error) {
    console.error('Error:', error);
    
    // 发送错误事件
    res.write(`event: error\ndata: ${JSON.stringify({ 
      error: 'Internal server error', 
      details: error.message 
    })}\n\n`);
    res.end();
  }
});

// 启动服务器
app.listen(port, () => {
  console.log(`SSE Server is running on http://localhost:${port}`);
});